package com.wzu.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
import java.util.Enumeration;

@WebServlet("/UpdateStock")
public class UpdateStockServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://gz-cynosdbmysql-grp-l5p5nhsn.sql.tencentcdb.com:26312/bookmanagement";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "Mouse1121332661!";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            conn.setAutoCommit(false); // 开启事务

            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                if (paramName.startsWith("stock_")) {
                    String bookId = paramName.substring(6);
                    int stock = Integer.parseInt(request.getParameter(paramName));
                    int available = Integer.parseInt(request.getParameter("available_" + bookId));

                    String sql = "UPDATE book SET stock_quantity = ?, available_quantity = ? WHERE book_id = ?";
                    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                        pstmt.setInt(1, stock);
                        pstmt.setInt(2, available);
                        pstmt.setString(3, bookId);
                        pstmt.executeUpdate();
                    }
                }
            }
            
            conn.commit(); // 提交事务
            response.sendRedirect("application/bookList.jsp?success=true");
            
        } catch (Exception e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            response.sendRedirect("application/bookList.jsp?error=true");
        } finally {
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}